//
//  WJChatVoicePanelView.m
//  WJAgroManagerDemo
//
//  Created by tqh on 2020/4/14.
//  Copyright © 2020 tqh. All rights reserved.
//

#import "WJChatVoicePanelView.h"
#import "WJChatVoicePanelCoverView.h"
#import "UIView+IM.h"
#import "UIColor+Hex.h"
#import "EMAudioPlayerHelper.h"
#import "EMAudioRecordHelper.h"
#import <AVFoundation/AVFoundation.h>
#import "WJIMChatAudioBoardAnimation.h"

@interface WJChatVoicePanelView()

@property (nonatomic, copy) NSString *audioPath;//音频路径
@property (nonatomic, assign) NSInteger audioLength;//音频路径
@property (nonatomic, strong) NSString *path;
@property (nonatomic) NSInteger maxTimeSecond;


@property (nonatomic,strong) UIButton *playButton;   //
@property (nonatomic,strong) UIButton *voiceButton;  //
@property (nonatomic,strong) UIButton *deleteButton; //
@property (nonatomic,strong) UILabel *timeLabel;     //时间文本

@property (nonatomic,strong) WJChatVoicePanelCoverView *finishView;
@property (nonatomic,strong) UIView *bgView;


@property (nonatomic ,strong) dispatch_source_t timer_gcd;  //GCD定时器
@property (nonatomic, assign) NSInteger currentTime;        //当前时间
@property (nonatomic,strong) WJIMChatAudioBoardAnimation *animationView;

@end

@implementation WJChatVoicePanelView


- (instancetype)initWithRecordPath:(NSString *)aPath
{
    self = [super init];
    if (self) {
        _path = aPath;
        _maxTimeSecond = 20;
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        [self addSubview:self.bgView];
        
        [self.bgView addSubview:self.animationView];
        [self.bgView addSubview:self.playButton];
        [self.bgView addSubview:self.voiceButton];
        [self.bgView addSubview:self.deleteButton];
        [self.bgView addSubview:self.timeLabel];
        
        [self addSubview:self.finishView];
        self.finishView.hidden = YES;
        self.playButton.hidden = YES;
        self.deleteButton.hidden = YES;
        [self addEvent];
        
    }
    return self;
}

- (void)addEvent {
    __weak typeof(self) myself = self;
    [self.finishView setDidItemBlock:^(NSInteger index) {
        myself.bgView.hidden = NO;
        if (index == 0) {
            //发送了不移除本地缓存
            myself.playButton.hidden = YES;
            myself.deleteButton.hidden = YES;
            myself.timeLabel.text = @"00:00";
        }
    }];
    
    [self.finishView setDidPlayBlock:^(BOOL play, UIButton * _Nonnull button) {
        
    }];
}

- (void)layoutSubviews {
    
    self.voiceButton.frame = CGRectMake((self.width - 86)/2, (self.height - 86)/2, 86, 86);
    self.animationView.frame = CGRectMake(0, 0, 200, 200);
    self.animationView.center = self.voiceButton.center;
    
    self.playButton.frame = CGRectMake(self.voiceButton.left - 40 - 46, self.voiceButton.centerY - 46/2, 46, 46);
    self.deleteButton.frame = CGRectMake(self.voiceButton.right + 40, self.voiceButton.centerY - 46/2, 46, 46);
    self.timeLabel.frame = CGRectMake(0, 6 + self.voiceButton.bottom, self.width, 20);
    self.bgView.frame = self.bounds;
    self.finishView.frame = self.bounds;
}

#pragma mark - 事件监听

- (void)playButtonPressed {
    self.finishView.audioPath = self.audioPath;
    self.finishView.audioLength = self.audioLength;
    
    self.finishView.hidden = NO;
    self.bgView.hidden = YES;
}

- (void)deleteButtonPressed {
    self.deleteButton.hidden = YES;
    self.playButton.hidden = YES;
    self.timeLabel.text = @"00:00";
    [self deleteFileWithPath:self.audioPath];
}

- (void)recordButtonTouchBegin
{
    [self.animationView startAnimation];
    [self _startRecord];
}

- (void)recordButtonTouchEnd
{
    [self.animationView stopAnimation];
    [self _stopRecord];
}

- (void)recordButtonTouchCancelBegin
{
}

- (void)recordButtonTouchCancelCancel
{
}

- (void)recordButtonTouchCancelEnd
{
    [self.animationView stopAnimation];
    [self _cancelRecord];
}

#pragma mark - Private

- (void)_startTimer
{
        dispatch_queue_t queue = dispatch_get_main_queue();
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
        dispatch_source_set_event_handler(timer, ^{
            self.currentTime ++;
            NSString *time = [self getMMSSFromSS:[NSString stringWithFormat:@"%ld",self.currentTime]];
            self.timeLabel.text = time;
        });
        
         //4.开始执行
        dispatch_resume(timer);
        self.timer_gcd = timer;
}

- (void)_stopTimer
{
    self.currentTime = 0;
    if (self.timer_gcd) {
        dispatch_source_cancel(self.timer_gcd);
        self.timer_gcd = nil;
    }
}


- (NSString *)getMMSSFromSS:(NSString *)totalTime{
    
    NSInteger seconds = [totalTime integerValue];
    
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",seconds/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
    
    NSLog(@"format_time : %@",format_time);
    
    return format_time;
}

-(void)deleteFileWithPath:(NSString *)pathString {

    NSFileManager* fileManager=[NSFileManager defaultManager];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:pathString];
    if (!blHave) {
        NSLog(@"no  have");
        return ;
    }else {
        BOOL blDele = [fileManager removeItemAtPath:pathString error:nil];
        if (blDele) {
            NSLog(@"dele success");
            }else {
            NSLog(@"dele fail");
        }
    }
}

#pragma mark - ---录制相关

- (void)_startRecord
{
    NSString *recordPath = [self.path stringByAppendingFormat:@"/%.0f", [[NSDate date] timeIntervalSince1970] * 1000];
    __weak typeof(self) weakself = self;
    [[EMAudioRecordHelper sharedHelper] startRecordWithPath:recordPath completion:^(NSError * _Nonnull error) {
        if (error) {
            [weakself recordButtonTouchCancelEnd];
            NSLog(@"报错了...%@",error.domain);
//            [EMAlertController showErrorAlert:error.domain];
        } else {
            [weakself _startTimer];
            if (weakself.delegate && [weakself.delegate respondsToSelector:@selector(chatBarRecordAudioViewStartRecord)]) {
                [weakself.delegate chatBarRecordAudioViewStartRecord];
            }
        }
    }];
}

- (void)_stopRecord
{
    [self _stopTimer];
    
    __weak typeof(self) weakself = self;
    [[EMAudioRecordHelper sharedHelper] stopRecordWithCompletion:^(NSString * _Nonnull aPath, NSInteger aTimeLength) {
        self.playButton.hidden = NO;
        self.deleteButton.hidden = NO;
        self.audioPath = aPath;
        self.audioLength = aTimeLength+1;
        NSLog(@"path = %@\nlength = %ld",aPath,aTimeLength);
        if (weakself.delegate && [weakself.delegate respondsToSelector:@selector(chatBarRecordAudioViewStopRecord:timeLength:)]) {
            [weakself.delegate chatBarRecordAudioViewStopRecord:aPath timeLength:aTimeLength];
        }
    }];
}

- (void)_cancelRecord
{
    [self _stopTimer];
    self.timeLabel.text = @"00:00";
    [[EMAudioRecordHelper sharedHelper] cancelRecord];
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBarRecordAudioViewCancelRecord)]) {
        [self.delegate chatBarRecordAudioViewCancelRecord];
    }
}


#pragma mark - 懒加载

- (UIView *)bgView {
    if (!_bgView) {
        _bgView = [UIView new];
    }
    return _bgView;
}

- (WJChatVoicePanelCoverView *)finishView {
    if (!_finishView) {
        _finishView = [[WJChatVoicePanelCoverView alloc]init];
    }
    return _finishView;
}

- (UIButton *)playButton {
    if (!_playButton) {
        _playButton = [UIButton new];
        [_playButton setImage:[UIImage imageNamed:@"WJChatVoicePanel_play_normal"] forState:UIControlStateNormal];
        [_playButton addTarget:self action:@selector(playButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    }
    return _playButton;
}

- (WJIMChatAudioBoardAnimation *)animationView {
    if (!_animationView) {
        _animationView = [[WJIMChatAudioBoardAnimation alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
    }
    return _animationView;
}

- (UIButton *)voiceButton {
    if (!_voiceButton) {
        _voiceButton = [UIButton new];
        [_voiceButton setImage:[UIImage imageNamed:@"WJChatVoicePanel_voice"] forState:UIControlStateNormal];
        [_voiceButton addTarget:self action:@selector(recordButtonTouchBegin) forControlEvents:UIControlEventTouchDown];
        [_voiceButton addTarget:self action:@selector(recordButtonTouchEnd) forControlEvents:UIControlEventTouchUpInside];
        [_voiceButton addTarget:self action:@selector(recordButtonTouchCancelBegin) forControlEvents:UIControlEventTouchDragOutside];
        [_voiceButton addTarget:self action:@selector(recordButtonTouchCancelCancel) forControlEvents:UIControlEventTouchDragInside];
        [_voiceButton addTarget:self action:@selector(recordButtonTouchCancelEnd) forControlEvents:UIControlEventTouchUpOutside];
        
    }
    return _voiceButton;
}

- (UIButton *)deleteButton {
    if (!_deleteButton) {
        _deleteButton = [UIButton new];
        [_deleteButton setImage:[UIImage imageNamed:@"WJChatVoicePanel_delete_normal"] forState:UIControlStateNormal];
        [_deleteButton addTarget:self action:@selector(deleteButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    }
    return _deleteButton;
}

- (UILabel *)timeLabel {
    if (!_timeLabel) {
        _timeLabel = [UILabel new];
        _timeLabel.textAlignment = NSTextAlignmentCenter;
        _timeLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightMedium];
        _timeLabel.textColor = [UIColor colorWithHexString:@"#BDBDBD"];
        _timeLabel.text = @"00:00";
    }
    return _timeLabel;
}

@end

